import {mutationWithClientMutationId, cursorForObjectInConnection} from "graphql-relay";
import {GraphQLBoolean, GraphQLInt, GraphQLString} from "graphql";
import UserType from "../../types/UserType";
import ProfileType from "../../types/ProfileType";
import {connectionFromType} from "../../connection";
import { Profile } from '../../models';

const AddProfileMutation = mutationWithClientMutationId({
  name: 'addProfile',
  inputFields: {
    name: { type: GraphQLString },
    autoUpdate: { type: GraphQLBoolean },
    isolate: { type: GraphQLBoolean },
    wtpRepEnable: { type: GraphQLBoolean },
    ssidRepEnable: { type: GraphQLBoolean },
    flowRepPeriod: { type: GraphQLInt },
    rateLimit: { type: GraphQLInt },
    vlanEnable: { type: GraphQLBoolean },
    fwDefaultEnable: { type: GraphQLBoolean },
    fwZoneEnable: { type: GraphQLBoolean },
    fwTrafficEnable: { type: GraphQLBoolean },
  },
  outputFields: {
    profileEdge: {
      type: connectionFromType('profile', ProfileType).edge,
      resolve: async ({ profileId }) => {
        const profiles = await Profile.findAll({});
        const profile = profiles.find(o => o.get('id') === profileId);
        return {
          cursor: cursorForObjectInConnection(profiles, profile),
          node: profile,
        };
      },
    },
    viewer: {
      type: UserType,
      resolve: async ({ viewer }) => viewer,
    }
  },
  mutateAndGetPayload: async({
    name,
    autoUpdate,
    isolate,
    wtpRepEnable,
    ssidRepEnable,
    flowRepPeriod,
    rateLimit,
    vlanEnable,
    fwDefaultEnable,
    fwZoneEnable,
    fwTrafficEnable,
  }, { viewer }) => {
    const profile = await Profile.create({
      name,
      autoUpdate,
      isolate,
      wtpRepEnable,
      ssidRepEnable,
      flowRepPeriod,
      rateLimit,
      vlanEnable,
      fwDefaultEnable,
      fwZoneEnable,
      fwTrafficEnable,
    });
    const profileId = profile.dataValues.id;
    return { profileId, viewer };
  },
});

export default AddProfileMutation;
